var sys_info = null;
var summaryXML='';
var skipDirectX=false;
var skipVC2008=false;
var skipVC2005=false;

function getSystemSettings()
{
    if(sys_info==null) sys_info=new Object();
    sys_info.vc2005 = SSN.Launcher.getRegistryString('machine','SOFTWARE\\Microsoft\\DevDiv\\VC\\Servicing\\8.0\\RED\\1033','SPName','');
    sys_info.vc2008 = SSN.Launcher.getRegistryString('machine','SOFTWARE\\Microsoft\\DevDiv\\VC\\Servicing\\9.0\\RED\\1033','SPName','');
    document.SSNLauncher.SSNLauncher_ReturnBool("GetSpecsHash");
    document.SSNLauncher.SSNLauncher_ReturnBool("GetSystemInfo");
    document.SSNLauncher.SSNLauncher_ReturnBool("GetAudioInfo");
    document.SSNLauncher.SSNLauncher_ReturnBool("GetVideoCardInfo");
    document.SSNLauncher.SSNLauncher_ReturnBool("GetVideoDriverInfo");
    document.SSNLauncher.SSNLauncher_ReturnBool("GetSummaryXML");
}

function getInternetExplorerVersion()
{
	var rv = -1; // Return value assumes failure.
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
		   rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

function AjaxUpdateMachineSpecsCall() 
{
    var req = init();
    req.onreadystatechange = processRequest;
        
    function init() 
    {
        if (window.XMLHttpRequest)
            return new XMLHttpRequest();
        else 
        if (window.ActiveXObject)
            return new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    function processRequest() 
    {
        if (req.readyState == 4) 
        {
            if (req.status == 200) 
            {/* kaplah! */ }
            else
            {
            	log("ERROR","Error updating machine specs, response was: "+req.status+"\n\n");
            	//alert("Error updating machine specs, response was: "+req.status+"\n\n");
            }
        }
    }

    this.execute = function(token)  
    {
       var url = platformurl+"machinespec";
       
       if((!sys_info)||(sys_info==null)) return;
       
       var sound_card = 'unk';
       if((sys_info.audio)&&(sys_info.audio.length>0))
       {
    	   sound_card = sys_info.audio[0];
    	   var x;
    	   for(x=1;x<sys_info.audio.length;x++)
    		   if((sound_card.length + sys_info.audio[x].length + 2)< 1000)
    			   sound_card+=', '+sys_info.audio[x];
       }
       
       var video_card = 'unk';
       if(sys_info.video_card)
    	   video_card = sys_info.video_card.vendor+' '+sys_info.video_card.make+' '+sys_info.video_card.model;
       
       var cpu_info = 'unk';
       if(sys_info.cpu)
    	   cpu_info = 'family: '+sys_info.cpu.family+', '+sys_info.cpu.cores+'core '+sys_info.cpu.mhz+'mhz '+sys_info.cpu.b+'b '+sys_info.cpu.mod+'mod '+sys_info.cpu.step+'step';
       
       var os_info = 'unk';
       if(sys_info.windows)
    	   os_info = 'Windows '+sys_info.windows.version+' SP'+sys_info.windows.sp;
       
       var mem_info = 'unk';
       if(sys_info.memory)
    	   mem_info = sys_info.memory;
       
       var lang_info = 'unk';
       if(lang)
    	   lang_info = lang;
       
       //var directx_info = 'n/a';
       
       var params = "token=" + user.token + "&"
       //			  + "directx=" + encodeURIComponent(directx_info) + "&" 
       			  + "language=" + encodeURIComponent(lang_info) + "&" 
       			  + "memory=" + encodeURIComponent(mem_info) + "&" 
       			  + "os=" + encodeURIComponent(os_info) + "&" 
       			  + "processor=" + encodeURIComponent(cpu_info) + "&" 
       			  + "soundcard=" + encodeURIComponent(sound_card) + "&" 
       			  + "vidcard=" + encodeURIComponent(video_card) + '&'
       			  + "xml=" + encodeURIComponent(summaryXML); 
       req.open("POST", url, true);
       req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
       req.setRequestHeader("Content-length", params.length);
       req.setRequestHeader("Connection", "close");
       req.send(params);
    }
}

function ReportMachineSpecs()
{
	var max=25;
	var historicHashes=new Array();
	var x=0;
	var found=false;
	for(x=0;x<max;x++)
	{
		var hash = SSN.Launcher.getSetting('SpecHash'+x);
		if((!hash)||(hash==undefined)||(hash==null)||(hash.length==0)||(hash=='undefined'))
			break;
		else
		{
			historicHashes[x]=hash;
			if(hash == sys_info.hash)
				found = true;
		}
	}
	if(!found)
	{
		if(historicHashes.length==max)
		{
			for(x=1;x<max;x++)
				historicHashes[x-1]=historicHashes[x];
		}
    	historicHashes[historicHashes.length]=sys_info.hash;
    	for(x=0;x<historicHashes.length;x++)
    		if((historicHashes[x])&&(historicHashes!=undefined))
	    	    SSN.Launcher.setSetting('SpecHash'+x, historicHashes[x]);
        SSN.Launcher.saveSettings();
        if(user) new AjaxUpdateMachineSpecsCall().execute(user.token);
	}
}

function ReportSummaryXML(value)
{
	summaryXML += value;
}

function ReportVideoDriverInfo(values)
{
    var vals=values.split('|');
    if(sys_info==null) sys_info=new Object();
    sys_info.video_driver=new Object();
    sys_info.video_driver.driver = vals[0];
    sys_info.video_driver.version = vals[1];
    sys_info.video_driver.WHQ = vals[2];
    //alert("Driver="+vals[0]+", Ver="+vals[1]+", WHQ="+vals[2]);
}

function ReportCPUInfo(values)
{
    var vals=values.split('|');
    if(sys_info==null) sys_info=new Object();
    sys_info.cpu=new Object();
    sys_info.cpu.cores = vals[0];
    sys_info.cpu.mhz = vals[1];
    sys_info.cpu.b = vals[2];
    sys_info.cpu.family = vals[3];
    sys_info.cpu.mod = vals[4];
    sys_info.cpu.step = vals[5];
    //alert("Cores="+vals[0]+", MHZ="+vals[1]+", b="+vals[2]+", Fam="+vals[3]+", Mod="+vals[4]+", Step="+vals[5]);
}

function ReportWindowsInfo(values)
{
    var vals=values.split('|');
    if(sys_info==null) sys_info=new Object();
    sys_info.windows=new Object();
    sys_info.windows.version=vals[0];
    sys_info.windows.sp=vals[1];
    //alert("Windows="+vals[0]+", SP="+vals[1]);
}

function ReportAudioInfo(values)
{
    if(sys_info==null) sys_info=new Object();
    if((sys_info.audio==null)||(sys_info.audio==NaN))
	    sys_info.audio=new Array(0);
    for(var i=0;i<sys_info.audio.length;i++)
    	if(sys_info.audio[i]==values)
    		return;
    sys_info.audio[sys_info.audio.length]=values;
    //alert("Audio["+sys_info.audio.length+"]="+values);
}

function ReportVideoCardInfo(values)
{
    var vals=values.split('|');
    if(sys_info==null) sys_info=new Object();
    sys_info.video_card=new Object();
    sys_info.video_card.make=vals[0];
    sys_info.video_card.vendor=vals[1];
    sys_info.video_card.model=vals[2];
    sys_info.video_card.vertex=vals[3];
    sys_info.video_card.pixel=vals[4];
    //alert("Make="+vals[0]+" ("+vals[1]+"), model="+vals[2]+", vertex="+vals[3]+", pixel="+vals[4]);
}

function ReportMemoryInfo(values)
{
    if(sys_info==null) sys_info=new Object();
    sys_info.memory = values;
    //alert("Memory="+values);
}

function ReportSpecsHash(values)
{
    if(sys_info==null) sys_info=new Object();
    sys_info.hash = values;
    //alert("SpecsHash="+values);
}

function SatisfyGameRequirements()
{
	if(sys_info==null)
	{
		getSystemSettings();
	}
	
    if((autoCloseStr == "PLAY")||(autoCloseStr == "CLOSE"))
    {
		log('INFO','Skipping requirement downloads');
    	return true;
    }
	var rootDir =  SSN.Launcher.expandString("{LAUNCHER_DIRECTORY}");
	if((!skipDirectX) && (!document.SSNLauncher.SSNLauncher_ReturnBool("CheckForD3DXVersion","int:9|int:38|")))
	{
	    patchCompleteCallBack=function()
	    {
			log('INFO','Launching update of DirectX');
	        var bLaunch = SSN.Launcher.runProcess(rootDir+'extras\\directx_Jun2010_redist.exe', '/T:"'+rootDir+'extras" /Q', rootDir+'\\extras', true, true);
	        if(!bLaunch)
	            alert(strings[lang]["Error Will Robinson! Error!"]);
	        else
	        	bLaunch = SSN.Launcher.runProcess(rootDir+'extras\\DXSETUP.exe', '', rootDir+'extras', true, true);
	        startPatch(pickedEnv, pickedProduct);
	    }
	    skipDirectX=true;
		log('INFO','Forcing patch of DirectX');
	    setTimeout('SSN.Patcher.addPackageList("DirectX", "http://'+external_manifest_url+'/sspatch/directx.packagelist", SSN.Launcher.getDirectory());',1);
		return false;
	}

	if((!skipVC2005) && (sys_info.vc2005 != 'RTM'))
	{
	    patchCompleteCallBack=function()
	    {
			log('INFO','Launching update of VCRT2005');
	        var bLaunch = SSN.Launcher.runProcess(rootDir+'extras\\vc2005redist_x86.exe', '/q:a /c:"VCREDI~3.EXE /q:a /c:""msiexec /i vcredist.msi /qb"""', rootDir+'extras', true, true);
	        if(!bLaunch)
	            alert(strings[lang]["Error Will Robinson! Error!"]);
	        startPatch(pickedEnv, pickedProduct);
	    }
	    skipVC2005=true;
		log('INFO','Forcing patch of VCRT2005');
	    setTimeout('SSN.Patcher.addPackageList("VCRT 2005", "http://'+external_manifest_url+'/sspatch/vc2005.packagelist", SSN.Launcher.getDirectory());',1);
		return false;
	}
	
	if((!skipVC2008) && (sys_info.vc2008 != 'SP1'))
	{
	    patchCompleteCallBack=function()
	    {
			log('INFO','Launching update of VCRT2008');
	        var bLaunch = SSN.Launcher.runProcess(rootDir+'extras\\vc2008redist_x86.exe', '/qb', rootDir+'extras', true, true);
	        if(!bLaunch)
	            alert(strings[lang]["Error Will Robinson! Error!"]);
	        startPatch(pickedEnv, pickedProduct);
	    }
	    skipVC2008=true;
		log('INFO','Forcing patch of VCRT2008');
	    setTimeout('SSN.Patcher.addPackageList("VCRT 2008", "http://'+external_manifest_url+'/sspatch/vc2008.packagelist", SSN.Launcher.getDirectory());',1);
		return false;
	}
	return true;
}
